package org.bt.common.validator;

import org.apache.commons.lang3.StringUtils;
import org.bt.common.constant.CommonConstant;
import org.bt.common.validator.aspect.DateTime;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * DateTimeValidator
 * <p>
 * Created on 2020/1/10
 *
 * @author tongw
 */
public class DateTimeValidator implements ConstraintValidator<DateTime, String> {

    private String format = CommonConstant.DateTimeFormat.YMD;

    @Override
    public void initialize(DateTime constraintAnnotation) {
        if (StringUtils.isNotBlank(constraintAnnotation.format())) {
            format = constraintAnnotation.format();
        }
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return true;
        }
        return ValidatorUtils.isDateTime(value, format);
    }
}
